package com.atguigu.yygh.hosp.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {
    //令牌的过期时间(通常30分钟) 24小时
    private static long tokenExpiration = 24*60*60*1000;
    //盐值
    private static String tokenSignKey = "123456";
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("YYGH-USER") //声明jwt面向的群体(说明该令牌是哪个项目下的,自定义的字符串)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) //设置令牌的过期时间
                .claim("userId", userId)  //载荷中的自定义业务数据
                .claim("userName", userName)
                //指定令牌的加密算法,以及盐值(提高令牌的安全性)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                //令牌的压缩格式
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //从jwt令牌中解析userId
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey(tokenSignKey) //解析令牌时,也需要指定盐值
                .parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        //get方法中的key一定和创建令牌时指定的key相同
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }

    public static void main(String[] args) {
//        String jwt = JwtHelper.createToken(100L, "tom");
//        System.out.println(jwt);
        Long userId = JwtHelper.getUserId("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSiox099ANDXYNUtJRSq0oULIyNLM0tDA2szA20lEqLU4t8kwBihkYQDh-ibmpQE0l-blKtQCQ774DQgAAAA.6aWA71dzdJxbwKKudrUi2L0UA_b7OJ8B6rbB_7dblFZ3OQLjOXry1zh62TcovJrKoV4ZQmEH4pvbtO2Y0shGaQ");
        String userName = JwtHelper.getUserName("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSiox099ANDXYNUtJRSq0oULIyNLM0tDA2szA20lEqLU4t8kwBihkYQDh-ibmpQE0l-blKtQCQ774DQgAAAA.6aWA71dzdJxbwKKudrUi2L0UA_b7OJ8B6rbB_7dblFZ3OQLjOXry1zh62TcovJrKoV4ZQmEH4pvbtO2Y0shGaQ");
        System.out.println(userId+userName);

    }
}
